package com.vanguard.p2p.controller;

import com.vanguard.p2p.base.BaseController;
import com.vanguard.p2p.business.domain.Member;
import com.vanguard.p2p.business.domain.MemberLoginLog;
import com.vanguard.p2p.business.service.IUserService;
import com.vanguard.p2p.constant.CommonReturnCode;
import com.vanguard.p2p.constant.UserReturnCode;
import com.vanguard.p2p.exception.ValidateException;
import com.vanguard.p2p.pojo.P2PResult;
import com.vanguard.p2p.utils.RSAUtils;
import com.vanguard.p2p.utils.RegexUtils;
import com.vanguard.p2p.utils.ServletUtils;
import com.vanguard.p2p.utils.SingletonLoginUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

/**
 * @author vanguard
 * @version 1.0
 * @describe 用户登录、注册表现层
 * @date 2018/02/23
 */
@Controller
@RequestMapping("/pass")
public class UserController extends BaseController {

    @Autowired
    private IUserService userService;
    /**
     * 用户登录界面
     * @return
     */
    @GetMapping(value = "/login")
    public String login() {
        return "user/login";
    }

    /**
     * 用户登录
     * @param userName
     * @param password
     * @return
     */
    @PostMapping(value = "/login")
    public Object login(String userName, String password) {
        // 服务器端，使用RSAUtils工具类对密文进行解密
        String passWord = RSAUtils.decryptStringByJs(password);

        Subject currentUser = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(userName, passWord);
        // 默认不记住我
        token.setRememberMe(false);
        try{
            currentUser.login(token);
            MemberLoginLog userLoginLog = new MemberLoginLog(new Date(), ServletUtils.getIpAddr(),
                    SingletonLoginUtils.getUserId(), ServletUtils.getUserOperatingSystem(),
                    ServletUtils.getUserBrowser());
            Integer count = userService.updateLogById(SingletonLoginUtils.getUserId(), userLoginLog);
            return new P2PResult(CommonReturnCode.SUCCESS, count);
        } catch (UnknownAccountException e) {
            logger.error(UserReturnCode.USER_NOT_EXIST.getMessage(), e);
            return new P2PResult(UserReturnCode.USER_NOT_EXIST);
        } catch (DisabledAccountException e) {
            logger.error(UserReturnCode.USER_SUSPEND.getMessage(), e);
            return new P2PResult(UserReturnCode.USER_SUSPEND);
        } catch (IncorrectCredentialsException e) {
            logger.error(UserReturnCode.WRONG_PASSWORD.getMessage(), e);
            return new P2PResult(UserReturnCode.WRONG_PASSWORD);
        } catch (ExcessiveAttemptsException e) {
            logger.error(UserReturnCode.ACCOUNT_LOCK.getMessage(), e);
            return new P2PResult(UserReturnCode.ACCOUNT_LOCK);
        }catch (RuntimeException e) {
            logger.error(CommonReturnCode.UNKNOWN_ERROR.getMessage(), e);
            return new P2PResult(CommonReturnCode.UNKNOWN_ERROR);
        }
    }

    /**
     * 用户注册界面
     * @return
     */
    @GetMapping(value = "/register")
    public String register() {
        return "user/register";
    }

    /**
     * 验证用户输入的用户名是否存在
     * @param userName
     * @return
     */
    @GetMapping(value = "/checkUserName")
    public Object checkUsername(@RequestParam("userName") String userName) {
        Boolean isExist = userService.getByUsername(userName);
        if(isExist) {
            return new P2PResult(CommonReturnCode.SUCCESS, false);
        }
        return new P2PResult(CommonReturnCode.SUCCESS, true);
    }

    /**
     * 用户注册
     * 验证用户输入的信息
     * @param user 用户注册输入的信息
     * @param registerCode 验证码
     * @param phoneCode 手机验证码
     * @return
     */
    @PostMapping(value = "/register")
    public Object register(@ModelAttribute("user") Member user, @RequestParam("registerCode") String registerCode, @RequestParam("phoneCode") String phoneCode) {
        if (!SingletonLoginUtils.validate(registerCode)) {
            return new P2PResult(UserReturnCode.REGISTER_CODE_ERROR);
        }

        if (StringUtils.isEmpty(user.getLoginPassword()) || !RegexUtils.isPassword(user.getLoginPassword())) {
            return new P2PResult(CommonReturnCode.BAD_REQUEST.getCode(), "密码长度6~20位，其中数字，字母和符号至少包含两种!");
        }
        try {
            userService.insertUser(user);
            return new P2PResult(CommonReturnCode.SUCCESS, user.getUserName());
        } catch (ValidateException e) {
            logger.error(e.getMessage(), e);
            return new P2PResult(e.getCode(), e.getMessage());
        }
    }
}
